//
//  WBWelcomeController.swift
//  SinaWeibo
//
//  Created by zhuangqianwei on 16/11/16.
//  Copyright © 2016年 zhuangqianwei. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
private let bottmMargin: CGFloat = 120
class WBWelcomeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //自动布局里面的frame不能直接修改，必须在layoutSubview里面修改
        setupUI()
    }
    //添加动画，动画效果需要改变图片等frame的y
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        //动画必须在这里设置才生效，不然从左上角出现
        startAnimation()
    }
    
    
    //动画效果
    private func startAnimation() {
        let offsetY = -(UIScreen.main.bounds.height - bottmMargin - icon.bounds.height)
        
        //更新约束
        self.icon.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view).offset(offsetY)
            
        }
        
        UIView.animate(withDuration: 1.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 7, options: [], animations:{
            //执行动画
            //提前更新约束
            self.view.layoutIfNeeded()
            
        }, completion: { (finished) -> () in
            
            //动画完成的回调
        UIView.animate(withDuration: 0.5, animations: { 
            self.welcomeLabel.alpha = 1
            
        }, completion: { (_) -> () in
            print("ok")
            //发出通知
            NotificationCenter.default.post(name: NSNotification.Name(kChoseRootViewController), object: nil)
//            UIApplication.shared.keyWindow?.rootViewController = WBTabBarController()
        })
        })
        
    }
    
    private func setupUI() {
        self.view.backgroundColor = UIColor.white
        //添加图片
        self.view.addSubview(icon)
        self.view.addSubview(welcomeLabel)
        self.welcomeLabel.alpha = 0
        //切圆角
        icon.layer.cornerRadius = 85 * 0.5
        icon.clipsToBounds = true
        
        
        //添加约束
        icon.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(-bottmMargin)
            make.size.equalTo(CGSize(width: 85, height: 85))
        }
        welcomeLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(icon)
            make.top.equalTo(icon.snp.bottom).offset(20)
        }
        //加载网络图片
        icon.sd_setImage(with: WBUserAccountViewModel.shared.headURL)

    }

    
    //懒加载头像图片和label
  private lazy var icon: UIImageView = UIImageView(image: #imageLiteral(resourceName: "avatar_default_big"))
    
  private lazy var welcomeLabel: UILabel = UILabel(title: "主人，您回来了", textCololr: UIColor.darkGray, fontSize: 14)
    
   }
